package com.hyy.blogtest.common.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyy.blogtest.common.pojo.Result;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


//写入http响应之前，进行响应包装
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice{

    @Autowired
    private ObjectMapper objectMapper;//Jackson库中Java对象和json转换用

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows//来自于lombok注解，自动在需要try catch的地方加捕获
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
            if(body instanceof String){//通常情况下不返回String类型
                return objectMapper.writeValueAsString(Result.ok(body));
            }else if(body instanceof Result<?>){
                return body;
            }
        return Result.ok(body);
    }
}
